<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/12/27
 * Time: 13:14
 */

namespace app\sales\lib;

final class ApiAuth
{
    private static $instance = null;
    public static function getInstance() : ApiAuth {
        if (empty(self::$instance)) {
            self::$instance = new static();
        }
        return self::$instance;
    }

    private function __construct()
    {
        $this->signSecret = '5d59a9c871b344a02645716affc6fb352a075ed0ea0a7204cc87ccc4b71d0b5320fec4bd4836f0e4ae043d9731d4deb4b0a60086ac7ab2de2d923b60a08482cd';
    }

    private $signSecret;

    /**
     * @param array $data 提交的数据数组
     * @return array
     */
    public function buildSign(array $data): array {

        $data['timestamp'] = strval(time());
        $data['nonce'] = hash('sha512', mt_rand(1000, 99999999));

        return [
            'nonce' => $data['nonce'],
            'timestamp' => $data['timestamp'],
            'sign' => $this->sign($data),
        ];
    }

    /**
     * @param array $data 提交的数据数组
     * @param array $signData 包含sign，timestamp，nonce的数组
     * @return bool
     */
    public function checkSign(array $data, array $signData): bool {
        $data['timestamp'] = $signData['timestamp'];
        $data['nonce'] = $signData['nonce'];

        return $this->sign($data) === $signData['sign'];
    }

    private function sign(array $data) {
        ksort($data);
        $str = http_build_query($data);
        $sign = hash_hmac('sha512', $str, $this->signSecret);

        return $sign;
    }
}